define([
    'angularAMD',
    'angular-localForage',
    'loading-bar',
    'mlab-recorder',
    'angular-ui-router',
], function (angularAMD) {
    'use strict';
    var app = angular.module('app', [
        'LocalForageModule',
        'mlab-recorder',
        'ui.router'
    ]);
    //config
    app.config(['$locationProvider', '$localForageProvider', '$stateProvider', '$urlRouterProvider', function ($locationProvider, $localForageProvider, $stateProvider, $urlRouterProvider) {

        //本地缓存设置
        $localForageProvider.config({
            name: 'mlab-app-recorder'
        });
        // $urlRouterProvider.otherwise('/list');
        $stateProvider
        .state('list',{
            url:'/list',
            views: {
                'content': angularAMD.route({
                    templateUrl: 'html/list.html',
                    controller: 'listCtrl',
                    controllerUrl: 'js/list'
                })
            }
        })  
        .state('list.liangcang',{
            url:'/liangcang',
            views: {
                'list': angularAMD.route({
                    templateUrl: 'html/liangcang.html',
                    controller: 'liangcangCtrl',
                    controllerUrl: 'js/liangcang'
                })
            }
        })
        .state('list.jianjiao',{
            url:'/jianjiao',
            views: {
                'list': angularAMD.route({
                    templateUrl: 'html/liangcang.html',
                    controller: 'jianjiaoCtrl',
                    controllerUrl: 'js/jianjiao'
                })
            }
        })
        .state('product',{
            url:'/product/:name?order_id&redirect_uri&from&type&thirdparty_id',
            views: {
                'content': angularAMD.route({
                    templateUrl: 'html/product.html',
                    controller: 'productCtrl',
                    controllerUrl: 'js/product'
                })
            }
        })
        .state('meilihui',{
            url:'/meilihui/:name?order_id&redirect_uri&from&type',
            views: {
                'content': angularAMD.route({
                    templateUrl: 'html/meilihui.html',
                    controller: 'meilihuiCtrl',
                    controllerUrl: 'js/meilihui'
                })
            }
        })
        .state('casio',{
            url:'/casio/:name?order_id&redirect_uri&from&type',
            views: {
                'content': angularAMD.route({
                    templateUrl: 'html/casio.html',
                    controller: 'casioCtrl',
                    controllerUrl: 'js/casio'
                })
            }
        })
        .state('secoo',{
            url:'/secoo/:name?order_id&redirect_uri&from&type',
            views: {
                'content': angularAMD.route({
                    templateUrl: 'html/secoo.html',
                    controller: 'secooCtrl',
                    controllerUrl: 'js/secoo'
                })
            }
        })
        //html5 Model
        $locationProvider.html5Mode(true);


        



    }]).controller('rootCtrl', ['$scope', '$rootScope', '$http', function($scope, $rootScope, $http){
        var server = 'http://www.malianghang.cn/wechat-api/config';
        $http({
            url: server,
            method: 'POST',
            data: {
                url: window.location.href
            }
        }).success(function (config) {
            $rootScope.$emit('wechatJsConfig', config);
            $rootScope.wechatJsConfig = config;
        });
    }])
    
    .directive('recorderButton', ['$rootScope', '$timeout', 'recorder', '$localForage', function($rootScope, $timeout, recorder, $localForage) {
        return {
            restrict: 'AEC',
            link: function($scope, element, attr) {
                $scope.tip = 'intro';
                $scope.recordingTip = '正在录音...';

                var panelId = '1';
                $scope.recordObject = {};
                //$scope.recordObject['isnew-' + panelId] = $scope.recordObject['isnew-' + panelId] == undefined ? true : $scope.recordObject['isnew-' + panelId];
                
                $scope.isNewRecord = $scope.recordObject['isnew-' + panelId];

                function getRecord(tag) {
                    var localWavName = tag + 'wav-' + panelId;
                    var localIdName = tag + 'id-' + panelId;
                    return {
                        id: $scope.recordObject[localIdName],
                        wav: $scope.recordObject[localWavName]
                    }
                }
                function setRecord(tag, id, wav) {
                    var localWavName = tag + 'wav-' + panelId;
                    var localIdName = tag + 'id-' + panelId;
                    $scope.recordObject[localIdName] = id;
                    $scope.recordObject[localWavName] = wav;
                }

                function getOldRecord(){
                    return getRecord('old');
                }

                function setOldRecord(id, wav){
                    return setRecord('old', id, wav);
                }

                function getNewRecord(){
                    return getRecord('new')
                }
                function setNewRecord(id, wav){
                    var data = getNewRecord();
                    if(data.id == id) return;
                    setOldRecord(data.id, data.wav);
                    setRecord('new', id, wav)
                    $scope.isNewRecord = $scope.recordObject['isnew-' + panelId] = true;
                  
                    

                    $scope.oldExist = (getOldRecord().id !== undefined);
                }


                if($rootScope.waveformEvent) $rootScope.waveformEvent();
                $rootScope.waveformEvent = $rootScope.$on('waveform', function(event, waveHeights, data, wavUrl, localId, warning){
                    $scope.ready = true;
                    if(warning) {
                        $scope.tip = 'warning';
                        return;
                    }       
                    $scope.tip = 'wave';
                  

                    
                    if(localId) {
                        setNewRecord(localId, wavUrl);
                        
                    }
                    
                });



                $scope.ready = false;


                //$localForage.clear();
                $localForage.bind($scope, {
                    key: 'record',
                    defaultValue: $scope.recordObject,
                    scopeKey: 'recordObject',
                    name: 'mlab-app-recorder'

                }).finally(function() {
                    $scope.isNewRecord = $scope.recordObject['isnew-' + panelId];
                    if($scope.isNewRecord) var record = getNewRecord();
                    else var record = getOldRecord();

                    $scope.oldExist = (getOldRecord().id !== undefined);
                    
                    if($rootScope.wechatJsConfig) {
                        recorder.init($rootScope.wechatJsConfig, record);
                        $scope.ready = true;
                    } else {
                        $rootScope.$on('wechatJsConfig', function(event, data){
                            recorder.init(data, record);
                            $scope.ready = true;
                        });
                    }

                    if($scope.isWeixin && !$scope.recordObject['isSlideShown']) {
                        $scope.openContentInfo();
                        $scope.recordObject['isSlideShown'] = true;
                    }
                });


                $scope.newRecord = function(){
                    if($scope.isNewRecord) return;
                    recorder.load(getNewRecord());
                    $scope.isNewRecord = $scope.recordObject['isnew-' + panelId] = true;
                };

                $scope.oldRecord = function(){
                    if(!$scope.isNewRecord) return;
                    recorder.load(getOldRecord());
                    $scope.isNewRecord = $scope.recordObject['isnew-' + panelId] = false;
                };

                var touchcancel = false;
                $scope.recorderPress = false;
                $scope.playPress = false;

                $scope.playRecord = function () {

                    $scope.playPress = true;
                    var scope = $scope
                    recorder.playRecord(function() {
                        $scope.playPress = false;
                        $scope.$apply(function () {
                        }); 
                    });
                };

                $scope.nextSlide = function() {
                    mySwiper.slideNext();
                };

                $scope.closeInfo = function() {
                    var step = document.getElementsByClassName('step');
                    for(var i = 0; i < step.length; i ++) {
                        step[i].style.display = 'none';
                    }
                };

                $scope.openContentHelp = function() {
                    var step2 = document.getElementById('step2');
                    step2.style.display = 'block';
                };

                $scope.getPhone = function () {
                    var step1 = document.getElementById('step1');
                    var step3 = document.getElementById('step3');
                    step1.style.opacity = 1;
                    step3.style.display = 'none';
                };

                $scope.content = true;
                $scope.size = false;
                $scope.moveToContent = function () {
                    $scope.content = true;
                    $scope.size = false;
                    mySwiper1.slideTo(0);
                };

                $scope.moveToSize = function () {
                    $scope.content = false;
                    $scope.size = true;
                    mySwiper1.slideTo(1);
                };

                var mySwiper = new Swiper('.content-info', {

                });

                var mySwiper1 = new Swiper('.product-tab', {
                    noSwipingClass: 'swiper-no-swiping',
                });

                

                element.on('touchstart', function (event) {
                    event.preventDefault();
                    if(touchcancel) {
                        //alert(1);
                        
                        return;
                    }
                    if(!$scope.ready) return;
                    $scope.recorderPress = true;
                    $scope.timeoutNumber = 3;
                    $scope.tip = 'countdown';
                    $scope.countdown = window.setInterval(function(){
                        $scope.timeoutNumber --;
                        
                        if($scope.timeoutNumber <= 0){
                            clearInterval($scope.countdown);
                            $scope.tip = 'recording';
                            clearTimeout($scope.recordTimeout);
                            $scope.recordTimeout = setTimeout(function(){
                                stopRecord()

                            }, 5000);
                            recorder.startRecord();
                            $scope.waveDataReady = false;
                            
                            
                        }
                        $scope.$digest();
                    }, 600);
                    $scope.$apply(function () {
                        $scope.$eval(attr.recorderButton);
                    });
                    
                });

                function stopRecord(){
                    if(!$scope.ready) return;
                    
                    clearInterval($scope.countdown);
                    if( $scope.tip !== 'recording') {
                        $scope.tip = 'intro';
                        $scope.recorderPress = false;
                    } else {
                        $scope.tip = 'uploading';
                    }
                     
                    $scope.$apply(function () {
                        $scope.$eval(attr.recorderButton);
                    }); 
                    recorder.stopRecord(function(result){
                        clearTimeout($scope.recordTimeout);
                        $scope.recorderPress = false;
                        if(result == 'tooshort') {
                            $scope.tip = 'tooshort';
                            $scope.ready = true;
                            $scope.btnText = '开始录音';
                           
                        } else {

                            $scope.ready = false;
                            
                            if( $scope.tip == 'uploading') {
                                $scope.tip = 'analysing';
                            } else {
                                $scope.tip = 'wave';
                                $scope.ready = true;
                            }
                        }
                        $scope.$apply(function () {
                            $scope.$eval(attr.recorderButton);
                        }); 
                            
                    });

                    
                    
                }
                element.on('touchend', function (event) {
                    stopRecord();
                    touchcancel = false;

                });

                element.on('touchcancel', function (event) {
                    $scope.recordingTip = '正在录音，再次点击按钮结束录音';
                    $scope.$apply(function () {
                        $scope.$eval(attr.recorderButton);
                    }); 
                    touchcancel = true;
                    var event = document.createEvent('Events');
                    event.initEvent('touchstart', true, true);
                    this.dispatchEvent(event);



                });


            }
        };
    }])
    return angularAMD.bootstrap(app);
});
